<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面标题 -->
    <div class="bg-white border-b border-gray-200 shadow-sm">
      <div class="container mx-auto px-4 py-5 flex justify-between items-center">
        <h1 class="text-2xl font-bold text-gray-800">表单数据管理</h1>
        <div class="flex items-center gap-3">
          <button 
            class="btn btn-primary flex items-center"
            @click="handleAddNew"
          >
            <i class="fa fa-plus mr-2"></i>
            <span>新增数据</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-6">
      <!-- 筛选和搜索区 -->
      <div class="bg-white rounded-lg shadow-sm p-5 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">表单类型</label>
            <select 
              v-model="filterFormType" 
              class="form-input w-full"
              @change="handleFilterChange"
            >
              <option value="">全部表单</option>
              <option value="contact">联系表单</option>
              <option value="feedback">反馈表单</option>
              <option value="registration">注册表单</option>
              <option value="survey">调查问卷</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">提交日期</label>
            <div class="flex gap-2">
              <input 
                type="date" 
                v-model="filterDateStart" 
                class="form-input flex-1"
                @change="handleFilterChange"
              >
              <span class="flex items-center text-gray-500">至</span>
              <input 
                type="date" 
                v-model="filterDateEnd" 
                class="form-input flex-1"
                @change="handleFilterChange"
              >
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">搜索</label>
            <div class="relative">
              <input 
                type="text" 
                v-model="searchKeyword" 
                class="form-input pl-10 w-full"
                placeholder="搜索表单内容..."
                @keyup.enter="handleSearch"
              >
              <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
          </div>
        </div>
        
        <div class="mt-4 flex justify-end gap-3">
          <button 
            class="btn btn-secondary"
            @click="resetFilters"
          >
            <i class="fa fa-refresh mr-1"></i>重置筛选
          </button>
          <button 
            class="btn btn-primary"
            @click="handleSearch"
          >
            <i class="fa fa-search mr-1"></i>搜索
          </button>
        </div>
      </div>
      
      <!-- 数据统计卡片 -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-primary">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">总数据量</p>
              <h3 class="text-2xl font-bold mt-1">{{ totalCount }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
              <i class="fa fa-database text-primary"></i>
            </div>
          </div>
          <p class="text-xs text-gray-500 mt-3">
            <i class="fa fa-arrow-up text-green-500"></i>
            <span class="ml-1">较昨日增长 12%</span>
          </p>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-green-500">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">今日新增</p>
              <h3 class="text-2xl font-bold mt-1">{{ todayCount }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-green-500/10 flex items-center justify-center">
              <i class="fa fa-calendar-check-o text-green-500"></i>
            </div>
          </div>
          <p class="text-xs text-gray-500 mt-3">
            <i class="fa fa-arrow-up text-green-500"></i>
            <span class="ml-1">较昨日增长 8%</span>
          </p>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-yellow-500">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">待处理</p>
              <h3 class="text-2xl font-bold mt-1">{{ pendingCount }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-yellow-500/10 flex items-center justify-center">
              <i class="fa fa-clock-o text-yellow-500"></i>
            </div>
          </div>
          <p class="text-xs text-gray-500 mt-3">
            <i class="fa fa-arrow-down text-red-500"></i>
            <span class="ml-1">较昨日减少 3%</span>
          </p>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-5 border-l-4 border-red-500">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">已处理</p>
              <h3 class="text-2xl font-bold mt-1">{{ processedCount }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-red-500/10 flex items-center justify-center">
              <i class="fa fa-check-circle text-red-500"></i>
            </div>
          </div>
          <p class="text-xs text-gray-500 mt-3">
            <i class="fa fa-arrow-up text-green-500"></i>
            <span class="ml-1">较昨日增长 15%</span>
          </p>
        </div>
      </div>
      
      <!-- 数据列表 -->
      <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  ID
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  表单类型
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  提交人信息
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  提交时间
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="item in formDataList" :key="item.id" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ item.id }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm">
                  <span 
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="getFormTypeClass(item.formType)"
                  >
                    {{ getFormTypeName(item.formType) }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  <div class="font-medium text-gray-900">{{ item.name }}</div>
                  <div class="text-gray-500">{{ item.email }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ formatDate(item.submittedAt) }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm">
                  <span 
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="getStatusClass(item.status)"
                  >
                    {{ getStatusName(item.status) }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button 
                    class="text-primary hover:text-primary/80 mr-3"
                    @click="handleViewDetails(item)"
                  >
                    查看
                  </button>
                  <button 
                    class="text-gray-600 hover:text-gray-900 mr-3"
                    @click="handleEdit(item)"
                    v-if="item.status === 'pending'"
                  >
                    编辑
                  </button>
                  <button 
                    class="text-green-600 hover:text-green-900 mr-3"
                    @click="handleMarkAsProcessed(item)"
                    v-if="item.status === 'pending'"
                  >
                    标记已处理
                  </button>
                  <button 
                    class="text-red-600 hover:text-red-900"
                    @click="handleDelete(item)"
                  >
                    删除
                  </button>
                </td>
              </tr>
              
              <!-- 无数据状态 -->
              <tr v-if="formDataList.length === 0 && !loading">
                <td colspan="6" class="px-6 py-12 text-center">
                  <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                    <i class="fa fa-file-text-o text-2xl text-gray-400"></i>
                  </div>
                  <h3 class="text-lg font-medium mb-2">暂无表单数据</h3>
                  <p class="text-gray-500 max-w-md mx-auto">
                    没有找到符合当前条件的表单数据，请尝试调整筛选条件或添加新数据
                  </p>
                </td>
              </tr>
              
              <!-- 加载状态 -->
              <tr v-if="loading">
                <td colspan="6" class="px-6 py-12 text-center">
                  <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                    <i class="fa fa-spinner fa-spin text-2xl text-gray-400"></i>
                  </div>
                  <p class="text-gray-500">加载中...</p>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 分页 -->
        <div v-if="formDataList.length > 0 && !loading" class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, totalCount) }} 条，共 {{ totalCount }} 条
          </div>
          
          <div class="flex items-center gap-2">
            <button 
              class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
              :disabled="currentPage === 1"
              @click="currentPage = currentPage - 1"
            >
              <i class="fa fa-chevron-left text-xs"></i>
            </button>
            
            <button 
              v-for="page in visiblePages" 
              :key="page"
              class="w-8 h-8 flex items-center justify-center rounded"
              :class="currentPage === page ? 'bg-primary text-white' : 'border border-gray-300 hover:bg-gray-50'"
              @click="currentPage = page"
            >
              {{ page }}
            </button>
            
            <button 
              class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
              :disabled="currentPage === totalPages"
              @click="currentPage = currentPage + 1"
            >
              <i class="fa fa-chevron-right text-xs"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 表单数据详情弹窗 -->
    <FormDataDetailDialog 
      :visible="detailVisible"
      :form-data="selectedFormData"
      @close="detailVisible = false"
      @status-change="handleStatusChange"
    />
    
    <!-- 新增/编辑表单弹窗 -->
    <FormDataEditDialog 
      :visible="editVisible"
      :form-data="formDataToEdit"
      :form-type="filterFormType"
      @close="editVisible = false"
      @save="handleSaveFormData"
    />
    
    <!-- 确认删除弹窗 -->
    <ConfirmDialog 
      :visible="deleteConfirmVisible"
      title="确认删除"
      content="确定要删除这条表单数据吗？此操作不可撤销。"
      @confirm="confirmDelete"
      @cancel="deleteConfirmVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted,watch } from 'vue'
import FormDataDetailDialog from '@/components/FormDataDetailDialog.vue'
import FormDataEditDialog from '@/components/FormDataEditDialog.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'

// 状态管理
const filterFormType = ref('')
const filterDateStart = ref('')
const filterDateEnd = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const formDataList = ref([])
const totalCount = ref(0)
const todayCount = ref(0)
const pendingCount = ref(0)
const processedCount = ref(0)

// 弹窗状态
const detailVisible = ref(false)
const editVisible = ref(false)
const deleteConfirmVisible = ref(false)
const selectedFormData = ref(null)
const formDataToEdit = ref(null)
const formDataToDelete = ref(null)

// 初始化页面数据
onMounted(() => {
  fetchFormData()
  fetchStatistics()
})

// 获取表单数据列表
const fetchFormData = async () => {
  loading.value = true
  try {
    // 模拟API请求
    const mockData = Array.from({ length: 15 }, (_, i) => ({
      id: i + 1 + (currentPage.value - 1) * pageSize.value,
      formType: ['contact', 'feedback', 'registration', 'survey'][Math.floor(Math.random() * 4)],
      name: `用户${i + 1 + (currentPage.value - 1) * pageSize.value}`,
      email: `user${i + 1 + (currentPage.value - 1) * pageSize.value}@example.com`,
      phone: `138${Math.floor(Math.random() * 100000000)}`,
      submittedAt: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
      status: Math.random() > 0.3 ? 'pending' : 'processed',
      content: `这是${['联系表单', '反馈表单', '注册表单', '调查问卷'][Math.floor(Math.random() * 4)]}的内容...`
    }))
    
    // 模拟筛选
    const filteredData = mockData.filter(item => {
      if (filterFormType.value && item.formType !== filterFormType.value) return false
      if (searchKeyword.value && !item.name.includes(searchKeyword.value) && !item.email.includes(searchKeyword.value)) return false
      return true
    })
    
    formDataList.value = filteredData
    totalCount.value = 56 // 模拟总数据量
    loading.value = false
  } catch (error) {
    console.error('获取表单数据失败:', error)
    loading.value = false
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // 模拟API请求
    todayCount.value = 8
    pendingCount.value = 15
    processedCount.value = 41
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchFormData()
}

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1
  fetchFormData()
}

// 重置筛选条件
const resetFilters = () => {
  filterFormType.value = ''
  filterDateStart.value = ''
  filterDateEnd.value = ''
  searchKeyword.value = ''
  currentPage.value = 1
  fetchFormData()
}

// 获取可见页码
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const endPage = Math.min(Math.ceil(totalCount.value / pageSize.value), startPage + maxVisible - 1)
  
  if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(totalCount.value / pageSize.value) || 1
})

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取表单类型名称
const getFormTypeName = (type) => {
  const typeMap = {
    'contact': '联系表单',
    'feedback': '反馈表单',
    'registration': '注册表单',
    'survey': '调查问卷'
  }
  return typeMap[type] || type
}

// 获取表单类型样式
const getFormTypeClass = (type) => {
  const classMap = {
    'contact': 'bg-blue-100 text-blue-800',
    'feedback': 'bg-purple-100 text-purple-800',
    'registration': 'bg-green-100 text-green-800',
    'survey': 'bg-yellow-100 text-yellow-800'
  }
  return classMap[type] || 'bg-gray-100 text-gray-800'
}

// 获取状态名称
const getStatusName = (status) => {
  return status === 'pending' ? '待处理' : '已处理'
}

// 获取状态样式
const getStatusClass = (status) => {
  return status === 'pending' 
    ? 'bg-yellow-100 text-yellow-800' 
    : 'bg-green-100 text-green-800'
}

// 查看详情
const handleViewDetails = (item) => {
  selectedFormData.value = { ...item }
  detailVisible.value = true
}

// 编辑数据
const handleEdit = (item) => {
  formDataToEdit.value = { ...item }
  editVisible.value = true
}

// 新增数据
const handleAddNew = () => {
  formDataToEdit.value = {
    id: null,
    formType: filterFormType.value || 'contact',
    name: '',
    email: '',
    phone: '',
    submittedAt: new Date().toISOString(),
    status: 'pending',
    content: ''
  }
  editVisible.value = true
}

// 保存表单数据
const handleSaveFormData = async (data) => {
  loading.value = true
  try {
    // 模拟保存API请求
    if (data.id) {
      // 更新现有数据
      const index = formDataList.value.findIndex(item => item.id === data.id)
      if (index !== -1) {
        formDataList.value.splice(index, 1, data)
      }
    } else {
      // 添加新数据
      const newId = Math.max(...formDataList.value.map(item => item.id), 0) + 1
      formDataList.value.unshift({ ...data, id: newId })
      totalCount.value++
    }
    
    editVisible.value = false
    loading.value = false
  } catch (error) {
    console.error('保存表单数据失败:', error)
    loading.value = false
  }
}

// 标记为已处理
const handleMarkAsProcessed = (item) => {
  const index = formDataList.value.findIndex(i => i.id === item.id)
  if (index !== -1) {
    formDataList.value[index].status = 'processed'
    pendingCount.value--
    processedCount.value++
  }
}

// 处理状态变更
const handleStatusChange = (id, status) => {
  const index = formDataList.value.findIndex(item => item.id === id)
  if (index !== -1) {
    formDataList.value[index].status = status
    if (status === 'processed') {
      pendingCount.value--
      processedCount.value++
    } else {
      pendingCount.value++
      processedCount.value--
    }
  }
}

// 删除数据
const handleDelete = (item) => {
  formDataToDelete.value = item
  deleteConfirmVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!formDataToDelete.value) return
  
  loading.value = true
  try {
    // 模拟删除API请求
    formDataList.value = formDataList.value.filter(
      item => item.id !== formDataToDelete.value.id
    )
    totalCount.value--
    
    if (formDataToDelete.value.status === 'pending') {
      pendingCount.value--
    } else {
      processedCount.value--
    }
    
    deleteConfirmVisible.value = false
    loading.value = false
  } catch (error) {
    console.error('删除表单数据失败:', error)
    loading.value = false
  }
}

// 监听页码变化
watch(currentPage, () => {
  fetchFormData()
})
</script>
    